<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!--- 搜索 --->
        <el-input
          v-model="query.name"
          clearable
          size="small"
          placeholder="输入机构名称搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <date-range-picker v-model="query.createDate" class="date-item" />
        <el-select
          v-model="query.enabled"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in enabledTypeOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="580px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        size="small"
        label-width="80px"
      >
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="form.name" style="width: 450px" />
        </el-form-item>

        <!-- <el-form-item label="机构编号" prop="code">
          <el-input v-model="form.code" style="width: 450px" />
        </el-form-item> -->

        <el-form-item label="联系地址" prop="address">
          <el-input v-model="form.address" style="width: 450px" />
        </el-form-item>

        <el-form-item label="邮政编码" prop="zipCode">
          <el-input v-model="form.zipCode" style="width: 178px" />
        </el-form-item>

        <el-form-item label="电话" prop="tel">
          <el-input
            v-model="form.tel"
            controls-position="right"
            style="width: 178px"
          />
        </el-form-item>

        <el-form-item label="机构排序" prop="orderRank">
          <el-input-number
            v-model.number="form.orderRank"
            :min="0"
            :max="999"
            style="width: 178px"
          />
        </el-form-item>

        <el-form-item label="状态" prop="enabled">
          <el-radio-group
            v-model="form.enabled"
            size="mini"
            controls-position="right"
            style="width: 178px"
          >
            <el-radio-button label="true">启用</el-radio-button>
            <el-radio-button label="false">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="上级机构" prop="pid">
          <treeselect
            v-model="form.pid"
            :load-options="loadOrg"
            :options="depts"
            :normalizer="normalizer"
            style="width: 450px"
            placeholder="选择上级类目"
          />
        </el-form-item>

        <el-form-item label="所在地区" style="margin-bottom: 0" prop="areaCode">
          <treeselect
            v-model="form.areaCode"
            :options="area"
            :load-options="loadArea"
            :normalizer="normalizerArea"
            style="width: 450px"
            placeholder="选择上所在地区"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2"
          type="primary"
          @click="crud.submitCU"
        >确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      lazy
      :load="getOrgDatas"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :data="crud.data"
      row-key="id"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
      <el-table-column label="名称" prop="name" />
      <el-table-column label="机构编号" prop="code" />
      <el-table-column label="排序" prop="orderRank" />
      <el-table-column label="状态" align="center" prop="enabled">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            :disabled="scope.row.id === 1"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeEnabled(scope.row, scope.row.enabled)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="创建日期" />
      <el-table-column
        v-if="checkPer(['admin', 'system:org,edit', 'system:org,del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
            :disabled-dle="scope.row.id === 1"
            msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import crudOrg from '@/api/system/org'
import crudArea from '@/api/system/area'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import DateRangePicker from '@/components/DateRangePicker'

const defaultForm = {
  id: null,
  name: null,
  code: null,
  address: null,
  zipCode: null,
  tel: null,
  pid: null,
  areaCode: null,
  orderRank: 999,
  enabled: 'true'
}
export default {
  name: 'Org',
  components: {
    Treeselect,
    crudOperation,
    rrOperation,
    udOperation,
    DateRangePicker
  },
  cruds() {
    return CRUD({
      title: '机构',
      url: 'api/sys/org/page',
      crudMethod: { ...crudOrg }
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      depts: [],
      area: [],
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        orderRank: [
          {
            required: true,
            message: '请输入序号',
            trigger: 'blur',
            type: 'number'
          }
        ]
      },
      permission: {
        add: ['admin', 'system:org,create'],
        edit: ['admin', 'system:org,edit'],
        del: ['admin', 'system:org,del']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '正常' },
        { key: 'false', display_name: '禁用' }
      ]
    }
  },
  methods: {
    getOrgDatas(tree, treeNode, resolve) {
      const params = { pid: tree.id }
      setTimeout(() => {
        crudOrg.getOrgs(params).then((res) => {
          resolve(res)
        })
      }, 100)
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      form.enabled = `${form.enabled}`
      this.depts = []
      this.area = []
      if (form.id != null) {
        if (form.pid === null) {
          form.pid = 0
        }
        this.getAllOrg(form.id)
        this.getAllArea(form.areaCode)
      } else {
        this.depts.push({ id: 0, name: '顶级类目', children: null })
        crudArea.getAreaTree(null).then((res) => {
          this.area = res
        })
      }
    },

    getAllOrg(id) {
      crudOrg.findAll(id).then((res) => {
        const children = res.map(function(obj) {
          if (!obj.leaf && !obj.children) {
            obj.children = null
          }
          return obj
        })
        this.depts = [{ id: 0, name: '顶级类目', children: children }]
      })
    },

    // 获取弹窗内部门数据
    loadOrg({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudOrg
          .getOrgTree({ pid: parentNode.id == '0' ? null : parentNode.id })
          .then((res) => {
            parentNode.children = res.map(function(obj) {
              if (!obj.leaf) {
                obj.children = null
              }
              return obj
            })
            setTimeout(() => {
              callback()
            }, 100)
          })
      }
    },

    loadArea({ action, parentNode, callback }) {
      console.info(this.area)
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudArea.getAreaTree({ pid: parentNode.id }).then((res) => {
          parentNode.children = res.map(function(obj) {
            if (!obj.leaf) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },

    getAllArea(areaCode) {
      crudArea.findAll(areaCode).then((res) => {
        const date = res
        this.area = date
      })
    },

    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    normalizerArea(node) {
      return {
        id: node.areaCode,
        label: node.name,
        children: node.children
      }
    },

    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      if (this.form.pid === null) {
        this.$message({
          message: '上级部门不能为空',
          type: 'warning'
        })
        return false
      }
      if (this.form.areaCode == null) {
        this.$message({
          message: '所在地区不能为空',
          type: 'warning'
        })
        return false
      }

      return true
    },
    // 改变状态
    changeEnabled(data, val) {
      console.info(data)
      this.$confirm(
        '此操作将 "' + val
          ? '禁用 '
          : '启用 ' + data.name + ' 部门, 是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          crudOrg
            .edit(data)
            .then((res) => {
              this.crud.notify('设置成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
            })
            .catch((err) => {
              data.enabled = !data.enabled
              console.log(err.response.message)
            })
        })
        .catch(() => {
          data.enabled = !data.enabled
        })
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
